<template>
  <!-- 添加和修改章节表单 -->
  <el-dialog :visible="dialogVisible" :title="dialogTitle" @close="close()">
    <el-form :model="chapter" :rules="rules" ref="chapterForm" label-width="80px">
      <el-form-item label="章节标题" prop="title">
        <el-input v-model="chapter.title" style="width: 400px" @keyup.enter.native="saveOrUpdate()"/>
      </el-form-item>
      <el-form-item label="章节排序">
        <el-input-number :min="0" v-model="chapter.sort" controls-position="right" style="width: 140px"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" @click="saveOrUpdate()">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { chapterApi } from '@/api'

export default {
  data() {
    return {
      dialogVisible: false, // 是否显示对话框
      dialogTitle: '添加章节', // 对话框标题
      chapter: {
        title: '',
        sort: 0
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      }
    }
  },
  methods: {
    open(chapterId) {
      this.dialogVisible = true
      this.dialogTitle = '添加章节'
      if (chapterId) {
        chapterApi.queryById(chapterId).then(response => {
          this.chapter = response.data.item
          this.dialogTitle = '修改章节'
        })
      }
    },
    close() {
      this.dialogVisible = false
      // 重置表单
      this.resetForm()
    },
    resetForm() {
      this.chapter = {
        title: '',
        sort: 0
      }
    },
    // 保存或更新
    saveOrUpdate() {
      this.$refs.chapterForm.validate((valid) => {
        if (valid) {
          if (!this.chapter.id) {
            this.saveData()
          } else {
            this.updateData()
          }
        } else {
          this.$message.warning('请完成必填项')
        }
      })
    },
    saveData() {
      this.chapter.courseId = this.$parent.$parent.courseId
      chapterApi.insert(this.chapter).then(response => {
        this.$message.success(response.message)
        // 关闭组件
        this.close()
        // 刷新列表
        this.$parent.fetchTreeList()
      })
    },
    updateData() {
      chapterApi.update(this.chapter).then(response => {
        this.$message.success(response.message)
        // 关闭组件
        this.close()
        // 刷新列表
        this.$parent.fetchTreeList()
      })
    }
  }
}
</script>

<style scoped>

</style>
